package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.feign.AdminFeign;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.HotArticlesService;
import com.heima.common.contans.article.ArticleConstans;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotArticlesServiceImpl implements HotArticlesService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void computeHotArticle() {
        String s = DateTime.now().minusDays(5).toString("yyyy-MM-dd 00:00:00");
        List<ApArticle> apArticles = articleMapper.selectList(Wrappers.<ApArticle>lambdaQuery().gt(ApArticle::getPublishTime, s));
        List<HotArticleVo> hotArticleVos  =computHotArticle(apArticles);
        cacheTagToRedis(hotArticleVos);
    }

    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private void cacheTagToRedis(List<HotArticleVo> hotArticleVos) {
        ResponseResult responseResult = adminFeign.findAll();
        List<AdChannel> adChannels = JSONArray.parseArray(JSON.toJSONString(responseResult.getData()), AdChannel.class);
        for (AdChannel adChannel : adChannels) {
            List<HotArticleVo> collect = hotArticleVos.stream().filter(p -> p.getChannelId().equals(adChannel.getId())).collect(Collectors.toList());
            sortAndCache(collect , ArticleConstans.HOT_ARTICLE_FIRST_PAGE + adChannel.getId());
        }

        sortAndCache(hotArticleVos , ArticleConstans.HOT_ARTICLE_FIRST_PAGE+ArticleConstans.DEFAULT_TAG);
    }

    private void sortAndCache(List<HotArticleVo> collect, String s) {
        collect.sort(new Comparator<HotArticleVo>() {
            @Override
            public int compare(HotArticleVo o1, HotArticleVo o2) {
                return o1.getScore() < o1.getScore() ? 1 : -1;
            }
        });
        if (collect.size() > 30){
            collect = collect.subList(0, 30);
        }
        if (collect.size() == 0){
            redisTemplate.opsForValue().set(s , "");
        }
        redisTemplate.opsForValue().set(s , JSON.toJSONString(collect));
    }

    private List<HotArticleVo> computHotArticle(List<ApArticle> apArticles) {
        List<HotArticleVo> list = new ArrayList<>();
        HotArticleVo hotArticleVo = null;
        if (!apArticles.isEmpty() && apArticles.size() > 0 ){
            for (ApArticle apArticle : apArticles) {
                hotArticleVo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle , hotArticleVo);
                Integer score = computeScore(apArticle);
                hotArticleVo.setScore(score);
                list.add(hotArticleVo);
            }
        }
        return list;
    }

    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getLikes() != null){
            score+=apArticle.getLikes()* ArticleConstans.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score+=apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score+=apArticle.getComment()*ArticleConstans.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score+=apArticle.getCollection()*ArticleConstans.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
